/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ch.haclyon;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ThreadPoolManager
 *
 * @author wangyin
 * @since 2021/07/21
 */
public class ThreadPoolManager {
    /**
     * threadPoolManager
     */
    private volatile static ThreadPoolManager threadPoolManager = null;

    /**
     * monitor1
     */
    private static final Object MONITOR_1 = new Object();

    /**
     * monitor2
     */
    private static final Object MONITOR_2 = new Object();

    /**
     * ExecutorService
     */
    private volatile ExecutorService executor;

    /**
     * ThreadPoolManager
     */
    private ThreadPoolManager() {
    }

    /**
     * ThreadPoolManager.getInstance
     *
     * @return ThreadPoolManager
     */
    public static ThreadPoolManager getInstance() {
        if (threadPoolManager == null) {
            synchronized (MONITOR_1) {
                if (threadPoolManager == null) {
                    threadPoolManager = new ThreadPoolManager();
                }
            }
        }
        return threadPoolManager;
    }

    /**
     * getExecutor
     *
     * @return ExecutorService
     */
    public ExecutorService getExecutor() {
        if (executor == null) {
            synchronized (MONITOR_2) {
                if (executor == null) {
                    executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                            60L, TimeUnit.SECONDS,
                            new SynchronousQueue<>());
                }
            }
        }
        return executor;
    }

    /**
     * execute runnable
     *
     * @param runnable runnable
     */
    public void execute(Runnable runnable) {
        getExecutor().execute(runnable);
    }

    /**
     * shutDown
     */
    public void shutDown() {
        getExecutor().shutdown();
    }

    /**
     * shutDownNow
     *
     * @return List<Runnable>
     */
    public List<Runnable> shutDownNow() {
        return getExecutor().shutdownNow();
    }
}
